package com.sneakxy.mybatis.commons.repository.config;

import java.io.Serializable;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.data.repository.Repository;
import org.springframework.data.repository.core.support.RepositoryFactorySupport;
import org.springframework.data.repository.core.support.TransactionalRepositoryFactoryBeanSupport;

/**
 * @author 潜行的青衣
 */
public class MybatisTransactionalRepositoryFactoryBean<T extends Repository<S, ID>, S, ID extends Serializable> extends TransactionalRepositoryFactoryBeanSupport<T, S, ID> {

	private SqlSessionFactory sqlSessionFactory;
	
	private SqlSessionTemplate sqlSessionTemplate;
	
	private MybatisCommonsConfiguration configuration;
	
	private Class<?> repositoryBaseClass;
	
	/**
	 * @param repositoryInterface
	 */
	protected MybatisTransactionalRepositoryFactoryBean(Class<? extends T> repositoryInterface) {
		super(repositoryInterface);
	}

	/* (non-Javadoc)
	 * @see org.springframework.data.repository.core.support.TransactionalRepositoryFactoryBeanSupport#doCreateRepositoryFactory()
	 */
	@Override
	protected RepositoryFactorySupport doCreateRepositoryFactory() {
		MybatisRepositoryFactoryBean repositoryFactory = new MybatisRepositoryFactoryBean();
		repositoryFactory.setSqlSessionFactory(sqlSessionFactory);
		repositoryFactory.setSqlSessionTemplate(sqlSessionTemplate);
		repositoryFactory.setConfiguration(configuration);
		repositoryFactory.setRepositoryBaseClass(repositoryBaseClass);
		return repositoryFactory;
	}
	
	public void setSqlSessionFactory(SqlSessionFactory sqlSessionFactory) {
		this.sqlSessionFactory = sqlSessionFactory;
	}

	@Override
	public void afterPropertiesSet() {
		this.sqlSessionTemplate = new SqlSessionTemplate(sqlSessionFactory);
		this.configuration = (MybatisCommonsConfiguration) this.sqlSessionTemplate.getConfiguration();
		super.afterPropertiesSet();
	}

}
